<template>
  <div class='question-new'>
    <!-- 标题开始 -->
   <el-card class="box-card" shadow="never">
    <div slot="header" class="clearfix">
      <span>试题录入</span>
    </div>
    <!-- 标题结束 -->

    <!-- ----------------------------分割线---------------------------------- -->
    <!-- 表单开始 -->
    <div class="el-card__body">
      <el-form  label-width="100px" ref="ruleForm" :model="ruleForm" :rules="rules"  class="question-form">
        <!-- 学科开始 -->
        <el-form-item label="学科：" prop="subjectID" required>
            <el-select
              v-model="ruleForm.subjectID"
              placeholder=""
              class="medium"
              @change="subjectID"
            >
              <el-option
                v-for="subject in subjectList"
                :key="subject.value"
                :label="subject.label"
                :value="subject.value"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- 学科结束 -->
        <!-- 目录开始 -->
        <el-form-item label="目录：" prop="catalogID" >
            <el-select v-model="ruleForm.catalogID" placeholder="" class="medium" clearable>
              <el-option
                v-for="item in catalogID"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- 目录结束 -->
        <!-- 企业开始 -->
        <el-form-item label="企业：" prop="enterpriseID" >
            <el-select placeholder="" v-model="ruleForm.enterpriseID" class="medium">
              <el-option
                v-for="item in enterpriseID"
                :key="item.id"
                :label="item.shortName"
                :value="item.id"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- 企业结束 -->
        <!-- 城市开始 -->
        <el-form-item
          label="城市："
          prop="city"
        >
            <el-select
              class="city1"
              v-model="ruleForm.province"
              @change="getcitys"
            >
              <el-option
                v-for="(item, index) in citySelect.province"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
            <el-select class="city2" v-model="ruleForm.city">
              <el-option
                v-for="(item, index) in citySelect.cityDate"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- 城市结束 -->
        <!-- 方向开始 -->
        <el-form-item label="方向：" prop="direction" >
            <el-select
              class="medium"
              v-model="ruleForm.direction"
            >
              <el-option
                v-for="(item, index) in direction"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- 方向结束 -->
        <!-- 题型开始 -->
        <el-form-item label="题型：" prop="questionType" >
            <el-radio-group  v-model="ruleForm.questionType" @change="questionType">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
        </el-form-item>
        <!-- 题型结束 -->
        <!-- 难度开始 -->
        <el-form-item label="难度：" prop="difficulty" >
            <el-radio-group v-model="ruleForm.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
        </el-form-item>
        <!-- 难度开始 -->
        <!-- 题干开始 -->
        <el-form-item label="题干：" prop="question" >
          <!--ref="myQuillEditor" -->
          <quill-editor
            v-model="ruleForm.question"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <!-- 题干结束 -->
        <!-- 选项开始 -->
        <el-form-item label="选项：" prop="options" v-show="ruleForm.questionType !== '3'">
          <div v-for="(item,index) in ruleForm.options" :key="index" id="select">
            <el-radio v-model="item.isRight" :label="1" v-if="ruleForm.questionType==1" @change="handel(item)">{{item.code}}：</el-radio>
            <!-- 多选 -->
             <el-checkbox v-model="item.isRight" v-if="ruleForm.questionType==2" :checked="item.isRight == 1">{{item.code}}：</el-checkbox>
             <!-- 输入框 -->
             <el-input v-model="item.title" placeholder=""></el-input>
             <div data-v-1ffc6d31="" class="avatar-uploader" style="margin-left: 4px;">
               <div tabindex="0" class="el-upload el-upload--text" @click="isupload(index)">
               <el-upload
                  class="upload-demo"
                  :show-file-list="false"
                  action="http://localhost:3000/upload"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  >
                  <img
                    :src="item.img"
                    v-if="item.img"
                    class="avatar"
                    style="
                        width: 100px;
                        height: 60px;
                    "
                  >
                  <!-- <el-button size="small" :style="{border:'none'}">点击上传</el-button> -->
                  <span v-else>点击上传</span>
                </el-upload>
               <i
                data-v-1ffc6d31=""
                class="el-icon-circle-close"
                @click="deleteImg()"
              ></i>
               <!-- <input type="file" name="file" class="el-upload__input"> -->
               </div>
            </div>
          </div>
          <div>
              <el-button
                type="danger"
                :disabled="this.ruleForm.questionType == 2 ? false : true"
                @click="addCheck"
              >+增加选项与答案</el-button>
          </div>
        </el-form-item>
        <!-- 选项结束 -->
        <!-- 解析视频开始 -->
        <el-form-item label="解析视频：" prop="videoURL">
            <el-input class="medium" v-model="ruleForm.videoURL"></el-input>
        </el-form-item>
        <!-- 解析视频结束 -->
        <!-- 答案解析开始 -->
        <el-form-item label="答案解析：" prop="answer" >
           <quill-editor
           class="quill"
            v-model="ruleForm.answer"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <!-- 答案解析结束 -->
        <!-- 题目备注开始 -->
        <el-form-item label="题目备注：" prop="remarks">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              class="medium"
              v-model="ruleForm.remarks"
            >
            </el-input>
        </el-form-item>
        <!-- 题目备注结束 -->
        <!-- 试题标签开始 -->
        <el-form-item
          label="试题标签："
          prop="tags"
        >
            <el-select v-model="ruleForm.tags" multiple  placeholder="" class="medium">
              <el-option
                v-for="item in tagslist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
        </el-form-item>
        <!-- 试题标签结束 -->
        <el-form-item>
          <el-button type="primary" @click="addForm(ruleForm)">确认提交</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表单结束 -->
  </el-card>
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys'
import { simple } from '@/api/hmmm/subjects'
import { direction } from '@/api/hmmm/constants'
import { list } from '@/api/hmmm/companys'
import { simple as catalogID } from '@/api/hmmm/directorys'
import { simple as tags } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
export default {
  name: 'QuestionNew',
  components: {
  },
  data () {
    return {
      ruleForm: {
        subjectID: null, // 学科*
        catalogID: null, // 目录*
        enterpriseID: null, // 企业*
        province: null, // 市*
        city: null, // 地区*
        direction: null, // 方向*
        questionType: '1', // 默认单选*
        difficulty: '1', // 困难默认值*
        options: [
          { code: 'A', img: null, title: null, isRight: 0 },
          { code: 'B', img: null, title: null, isRight: 0 },
          { code: 'C', img: null, title: null, isRight: 0 },
          { code: 'D', img: null, title: null, isRight: 0 }
        ], // 单选选项 默认值\
        question: null, // 题干*
        videoURL: null, // 解析视频s
        answer: null, // 答案解析*
        remarks: null, // 文本域题目备注
        tags: [] // 试题标签

      },
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link'] // 图片 链接
          ]
        },
        placeholder: ''
      },
      subjectList: [], // 学科列表
      citySelect: {
        province: [],
        cityDate: []
      }, // 获取城市
      direction: {}, // 获取方向
      enterpriseID: [], // 获取企业
      companysList: [],
      catalogID: [], // 获取目录
      tagslist: [], // 获取标签
      options: {
        optionsA: '',
        optionsB: '',
        optionsC: '',
        optionsD: ''
      },
      option: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      rules: {
        subjectID: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        options: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ]
      },
      isoptions: true,
      selectCheck: true,
      parsing: '',
      textarea: '',
      imgIndex: null,
      imageUrl: ''
    }
  },
  created () {
    this.getSubjectId()
    this.getCityData()
    this.getdirection()
    this.getenterpriseID()
    this.getDetail()
  },
  rules: {

  },
  methods: {
    // 获取学科列表开始
    async getSubjectId () {
      try {
        const { data } = await simple()
        this.subjectList = data
      } catch (err) {
        // console.log(err, 122)
        this.$message.error('获取学科列表失败！！')
      }
    },
    // 获取学科列表结束
    // 获取城市列表开始
    getCityData () {
      this.citySelect.province = provinces()
    },
    // 获取城市列表结束
    // 获取地区列表开始
    async getcitys (val) {
      try {
        const data = await citys(val)
        this.citySelect.cityDate = data
        this.ruleForm.city = null
      } catch (err) {
        // console.log(err)
        this.$message.error('获取地区列表失败！！')
      }
    },
    // 获取地区列表结束
    // 获取方向开始
    getdirection () {
      this.direction = direction
    },
    // 获取方向结束
    // 获取企业开始
    async getenterpriseID () {
      try {
        const { data } = await list()
        this.enterpriseID = data.items
      } catch (err) {
        // console.log(err)
        this.$message.error('获取企业列表失败！！')
      }
    },
    // 获取企业结束
    // 选择学科渲染目录/标签开始
    async subjectID (val) {
      this.ruleForm.catalogID = ''
      try {
        const { data: res1 } = await catalogID({
          subjectID: val
        })
        const { data: res2 } = await tags({
          subjectID: val
        })
        this.catalogID = res1
        this.tagslist = res2
      } catch (err) {
        // console.log(err)
        this.$message.error('获取目录标签失败！！')
      }
    },
    // 选择学科渲染目录/标签结束
    // 点击更改题型开始
    questionType (val) {
      if (val === '1') {
        this.isoptions = true
        this.selectCheck = true
      } else if (val === '2') {
        this.isoptions = true
        this.selectCheck = false
        this.disabled = true
        console.log(this.checkList)
      } else if (val === '3') {
        this.isoptions = false
      }
    },
    // 点击更改题型结束
    // 点击添加多选选项开始
    addCheck () {
      const arr = this.ruleForm.options
      if (arr.length <= 7) {
        arr.push({
          code: String.fromCharCode(65 + arr.length), img: null, title: null, isRight: 0
        })
      } else {
        this.$message.error('超过最大选项')
      }
    },
    // 点击添加多选选项结束
    addForm (ruleForm) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.$route.query.id) {
            this.ruleForm.tags = this.ruleForm.tags.join()
            await update(this.ruleForm)
            this.$router.push('list')
          }
          this.ruleForm.tags = this.ruleForm.tags.join()
          // console.log(this.ruleForm)
          await add(this.ruleForm)
          this.$router.push('list')
        } else {
          return false
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.ruleForm.options[
        this.imgIndex
      ].img = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 删除图片
    deleteImg () {
      this.ruleForm.options[this.imgIndex].img = ''
    },
    // 单选互斥
    handel (currentItem) {
      this.ruleForm.options.forEach(item => {
        if (item !== currentItem) {
          item.isRight = 0
        }
      })
    },
    isupload (index) {
      this.imgIndex = index
    },
    // // 点击修改渲染页面
    async getDetail (id) {
      const sid = this.$route.query.id
      if (sid) {
        const { data } = await detail({ id: sid })
        this.ruleForm = data
        this.ruleForm.tags = this.ruleForm.tags.split(',')
        // 修改城市地区不能没有数据
        this.citySelect.cityDate = await citys(data.province)
        this.ruleForm.city = this.citySelect.cityDate[0]
        // this.ruleForm.city = ''
        // 修改目录获取到的值为value
        const res = await catalogID()
        // console.log(res)
        const i = res.data.find(item => {
          return item.value === data.catalogID
        })
        // console.log(i)
        this.catalogID.push(i)
      } else {
        return false
      }
    }
  }
}

</script>

<style scoped lang='less'>
.question-new {
  padding: 20px;
  .el-card__header {
    padding: 18px 20px;
    border-bottom: 1px solid #ebeef5;
  }

}
/deep/ .ql-editor p {
  height: 200px;
}
.question-form {
  .medium {
    width: 400px;
  }
  .city1 {
    width: 198px;
  }
  .city2 {
    width: 198px;
    margin-left: 4px;
  }
  .rich-text {
    height: 200px;
    display: block;
  }
    .option_item {
      padding-bottom: 20px;
      line-height: 60px;
      text-align: center;
      .avatar-uploader {
        display: inline-block;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        width: 100px;
        height: 60px;
        line-height: 60px;
        margin-left: 5px;
      }
      .el-radio {
        margin: 0;
      }
      span {
        font-size: 14px;
      }
      .upload-close {
        position: absolute;
        top: 0;
        right: 0;
        transform: translate(50%,-50%);
        background: #fff;
        font-size: 18px;
        color: #999;
      }

      .options-input {
        background-color: #fff;
        background-image: none;
        border-radius: 4px;
        box-sizing: border-box;
        color: #606266;
        display: inline-block;
        font-size: 16px;
        outline: 0;
        // transition: border-color .2s cubic-bezier(.645,.045,.355,1);
        width: 240px;
        height: 36px;
        line-height: 36px;
      }
  }
}
#select{
  display: flex;
  margin-bottom: 30px;
  .el-input--medium{
    width: unset;
  }
  .el-radio{
    margin-right: 0;
    line-height: 56px;
  }
  .el-checkbox{
    line-height: 56px;
  }
  /deep/.el-input__inner{
    width: 280px;
    margin-top: 10px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 100px;
    height: 60px;
    line-height: 60px
    }
    .avatar-uploader i {
    position: absolute;
    right: 0;
    top: 0;
    -webkit-transform: translate(50%,-50%);
    transform: translate(50%,-50%);
    background: #fff;
    font-size: 18px;
    color: #999;
    }
}
</style>
